package com.itheima.sh.controller;

import com.itheima.sh.pojos.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("consumer")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("{id}")
    // queryByIdFallBack: 绑定降级方法名
    @HystrixCommand(fallbackMethod = "queryByIdFallBack")
    public Map queryById(@PathVariable("id") String id) {

        // 1.获取URL(硬编码)
//        String url = "http://localhost:8081/user/" + id;

        // 1.从Eureka中获取服务的实例（IP、PORT）
        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        ServiceInstance serviceInstance = instances.get(0);

        /*String url =
                "http://"+serviceInstance.getHost()
                        +":"+serviceInstance.getPort()+"/user/" +id;*/

        // 1.Ribbon实现
        String url = "http://user-service/user/" + id;

        /*if ("itheima".equals(id)) {

            throw new RuntimeException("itheima");
        }
*/
        // 2.调用RestTemplate的getForObject方法，指定url地址和返回值类型
        Map user = restTemplate.getForObject(url, Map.class);

        // 3.得到结果
        System.out.println(user);

        return user;
    }

    // 降级方法
    public Map queryByIdFallBack(@PathVariable("id") String id) {

        return new HashMap();
    }
}
